================================================================================
 PPLN OPA Propagation Simulation - README
================================================================================

This project simulates a type-0 quasi-phase-matched (QPM) PPLN optical
parametric amplifier (OPA): a pump beam at 1064 nm amplifies a seed signal
beam (~1561 nm) inside a periodically-poled lithium niobate crystal,
generating an idler beam (~3342 nm) via three-wave mixing (chi(2)
nonlinearity). The code numerically propagates the three coupled optical
fields (pump, signal, idler) through the crystal in 3D+1 (x, y, t), including
diffraction, group-velocity dispersion, and full pump/signal/idler depletion
(i.e. no undepleted-pump approximation). It was used to generate the
simulated power curves and z-evolution figures in the associated manuscript.

There are two files:

    propagation.py               - the physics/engine module (no simulation
                                    is run just by importing it)
    propagation_simulation.ipynb - the notebook that sets parameters, calls
                                    the engine, and produces all plots/CSVs

================================================================================
 1. propagation.py  -  the simulation engine
================================================================================

This module contains all the physics and numerics. It is imported into the
notebook with `from propagation import *`, so every function/constant below
becomes directly available in the notebook (no `propagation.` prefix needed).

--------------------------------------------------------------------------------
1.1 Constants
--------------------------------------------------------------------------------
    c0    - speed of light in vacuum (m/s)
    eps0  - vacuum permittivity (F/m)

--------------------------------------------------------------------------------
1.2 Material properties: 5% MgO-doped LiNbO3 (PPLN) Sellmeier equations
--------------------------------------------------------------------------------
    n_ppln(T, wvl, theta=90, type="e")
        Refractive index (ordinary "o" or extraordinary "e") at temperature T
        (deg C) and wavelength wvl (m), using the temperature-dependent
        Sellmeier equation. `theta` is the angle between the propagation
        direction and the optic axis (90 deg = the "e" index reduces to the
        simple uniaxial extraordinary index, used here for type-0 QPM).

    ng_ppln(T, wvl, type="e")
        Group index n_g = n - wvl * dn/dwvl, derived analytically from the
        same Sellmeier equation.

    D_ppln(T, wvl, type="e")
        Group-velocity dispersion (GVD), returned in s/m^2. The notebook
        converts this to the more familiar fs^2/mm for reporting/plotting.

    plot_ppln_properties(wvl, temp, x_axis, type="e", theta=90, filename=None)
        Convenience plot of refractive index, group index and GVD either
        versus wavelength or versus temperature (set with x_axis). Saves a
        PDF to output_plots/ if `filename` is given.

--------------------------------------------------------------------------------
1.3 Split-step propagation operators
--------------------------------------------------------------------------------
The propagation uses the standard symmetric split-step Fourier method: each
step dz applies (linear half-step) -> (nonlinear full-step) -> (linear
half-step), alternating between real space (for the nonlinear chi(2) mixing)
and Fourier space (for the linear diffraction/dispersion operators).

    dispersion_phase(omega_offset, lambda_carrier, dz, T_crystal)
        Returns the per-step frequency-domain phase factor exp(-i*D/2 *
        omega^2 * dz/2) applied along the time axis to model group-velocity
        dispersion for one field (pump, signal or idler).

    diffraction_phase(n, no, ne, kx, ky, dz, k_carrier, theta)
        Returns the per-step transverse-k-space phase factor modelling
        diffraction (paraxial propagation) for a beam in a uniaxial crystal,
        accounting for the walk-off/anisotropy between the ordinary and
        extraordinary axes.

    nonlinear_rhs_vec(z, A_p, A_s, A_i, kappa_p, kappa_s, kappa_i,
                       alpha_p, alpha_s, alpha_i, Delta_k)
        The three coupled-wave ODEs (right-hand sides) for chi(2)
        three-wave mixing with phase mismatch Delta_k and linear absorption
        (alpha_p/s/i), evaluated at longitudinal position z.

    apply_nonlinear(...)  /  apply_nonlinear_euler(...)
        Advance the nonlinear part of the coupled-wave equations by one step
        dz, using 4th-order Runge-Kutta (apply_nonlinear, used by
        run_simulation) or a simple forward-Euler step (apply_nonlinear_euler,
        kept for reference/testing only).

    run_simulation(As, disps, diffs, dz, kappas, alphas, Delta_k, L_total,
                    save_every=10)
        The main propagation loop. `As = (A_p, A_s, A_i)` are the complex
        field envelopes at the crystal input, each a 3D array of shape
        (Nx, Ny, Nt) (transverse x, transverse y, time). `disps`/`diffs` are
        the pre-computed per-step dispersion/diffraction phase factors for
        each of the 3 fields (from dispersion_phase / diffraction_phase).
        `kappas` = (kappa_p, kappa_s, kappa_i) are the nonlinear coupling
        coefficients, `alphas` the absorption coefficients, `Delta_k` the
        phase mismatch, `L_total` the crystal length, `dz` the step size.
        Returns (As_z, z_positions), where As_z holds the field at every
        `save_every`-th z-step (to control memory/output size) and
        z_positions are the corresponding z coordinates (m).

--------------------------------------------------------------------------------
1.4 Post-processing / plotting helpers
--------------------------------------------------------------------------------
    load_simulation_results(filename)
        Loads a previously-saved simulation (see notebook section 2.4) from
        output_simulations/{filename}_*.npy and reconstructs the full
        (mirrored) time axis.

    plot_imshow(...), plot_power_z(...), plot_pulse_power(...),
    plot_pulse_spectra_at_output(...)
        Helpers to plot 2D field maps, average power vs. propagation
        distance, temporal pulse shapes, and output spectra.

    calculate_M2(...), compute_M2(...), compute_M2x(...)
        Beam-quality-factor (M^2) calculation utilities, used to check that
        the simulated beams stay close to diffraction-limited (M^2 ~ 1)
        through the crystal.

    plot_customize()
        Sets global matplotlib rcParams (serif font, inward ticks, Computer
        Modern math font, etc.) for consistent, publication-style figures.
        Called once near the top of the notebook.

================================================================================
 2. propagation_simulation.ipynb  -  the simulation notebook
================================================================================

This is the main notebook: it defines all physical/numerical parameters,
calls the propagation.py engine, and produces every plot, CSV and .npz field
file used for the manuscript. Run cells top-to-bottom. The notebook is
organised into these sections:

--------------------------------------------------------------------------------
2.1 Refractive index / GVD visualisation
--------------------------------------------------------------------------------
Quick sanity-check plots of n, n_g and GVD vs. wavelength and vs. temperature
for the PPLN crystal, using plot_ppln_properties from propagation.py.

--------------------------------------------------------------------------------
2.2 Simulation setup
--------------------------------------------------------------------------------
    Material, wavelength, absorption
        Crystal temperature, pump/signal/idler wavelengths (idler is derived
        from energy conservation: 1/lambda_i = 1/lambda_p - 1/lambda_s),
        nonlinear coefficient d_eff, facet reflectivities R_p/R_s/R_i,
        refractive/group indices, nonlinear coupling coefficients kappa_p/s/i,
        and the QPM phase mismatch Delta_k (computed from the grating period,
        including its thermal expansion with temperature).

    Simulation parameters
        Grid definition: Nx, Ny transverse points and spacing dx, dy; Nt time
        points and time window (multiples of the FWHM pulse duration tau_p);
        Nz longitudinal steps over the crystal length L_total (giving the
        step size dz). Also builds the transverse (X, Y) and time (t) axes,
        and the Fourier-space kx, ky, omega grids used by the propagation
        operators.

    Beam parameters
        Pump/signal average powers and repetition rate; measured beam waists
        w0_p, w0_s (assumed equal) with an axial focus offset between them
        (lens_focal_shift) to account for the achromatic lens's chromatic
        focal shift. Builds the complex Gaussian-beam q-parameters and
        constructs the actual input field envelopes A_p, A_s (Gaussian in
        both time and space) and A_i (zero at the input, since the idler is
        generated inside the crystal). Prints a few analytic sanity checks
        (expected pulse energy/power vs. what the constructed field
        actually integrates to).

--------------------------------------------------------------------------------
2.3 Diverse plots of input
--------------------------------------------------------------------------------
Plots the pump/signal temporal profiles and transverse spatial profiles at
the crystal input, as a visual check before running the full propagation.

--------------------------------------------------------------------------------
2.4 Simulation
--------------------------------------------------------------------------------
Builds the per-step dispersion/diffraction phase operators (dispersion_phase,
diffraction_phase) for all 3 fields, runs a single example propagation with
run_simulation, and saves the raw fields/z-positions/parameters to
output_simulations/tests/ via .npy files (a quick single-case example, not
part of the main power sweeps below).

--------------------------------------------------------------------------------
2.5 SNLO inputs
--------------------------------------------------------------------------------
Prints a formatted table of equivalent input parameters for the SNLO
"2D-mix-LP" tool, useful for cross-checking this custom simulation against
the widely-used SNLO software.

--------------------------------------------------------------------------------
2.6 Power & crystal-length parameter sweeps
--------------------------------------------------------------------------------
Batch simulations used to reproduce the manuscript's power-scaling figures.
All sweep cells are resumable: re-running a cell skips any case whose output
file already exists on disk, so an interrupted run can simply be re-executed.

    Multi-length power sweep
        Sweeps matched pump/signal power pairs (power_cases_all) across five
        crystal (PCF) lengths, matching the experimental data points. For
        every case it saves: the full field data (.npz) to
        output_simulations/power_scan/fields/, a per-case z-evolution CSV to
        output_simulations/power_scan/z_evolution/, and a final-value
        summary table (output_simulations/power_scan/all_lengths_scan_
        results.csv).

    Fixed-pump, broad signal-power sweep
        Pump power held fixed at one crystal length (969 mW, 0.15 m) while
        the signal power is swept over several decades (signal_uW_list), to
        trace out the idler-vs-signal saturation curve. Saves the same style
        of per-case z-evolution CSV as above (re-using the calc_energy_vs_z /
        safe_name helpers defined in the multi-length sweep cell).

    Fields + z-evolution + summary CSV for the fixed-pump signal sweep
        A fully self-contained companion to the sweep above: for every case
        it (re)computes and saves the full field data (.npz), the per-case
        z-evolution CSV, and a final-value summary CSV
        (fixed_pump_vary_signal_results.csv), matching the multi-length
        sweep's format. Everything is written to an external OneDrive data
        folder (see `save_dir` at the top of the cell) rather than the local
        output_simulations/ folder. Resumable: skips any case whose field
        file already exists.

--------------------------------------------------------------------------------
2.7 Full z-resolution for the High/Optimum/Low comparison cases
--------------------------------------------------------------------------------
The sweeps above save z-evolution at a coarse step (save_every_z=20) to keep
file sizes small. For three representative cases (High = 94 mW signal at
0.26 m, Optimum = 350 uW signal at 0.15 m, Low = 10 uW signal at 0.15 m),
this cell re-runs the propagation at full resolution (save_every=1, all 151
z-steps) and saves to output_simulations/power_scan/z_evolution_fine/, so the
final comparison plots have smooth curves.

Finally, a plotting cell reproduces the manuscript-style comparison figure:
a 3x2 grid (rows = Pump/Signal/Idler, columns = linear/log power scale)
showing all three High/Optimum/Low cases overlaid, colored with a viridis
colormap and labelled (a)-(f).

================================================================================
 3. Requirements
================================================================================
Python >= 3.9, with: numpy, scipy, matplotlib, pandas, tqdm
(see requirements.txt).

================================================================================
 4. Output folder structure (created automatically on first run)
================================================================================
    output_plots/                                     - PDF plots from propagation.py helpers
    output_simulations/tests/                          - single example-run fields/params
    output_simulations/power_scan/fields/              - .npz fields, multi-length sweep
    output_simulations/power_scan/z_evolution/         - per-case z-evolution CSVs (coarse)
    output_simulations/power_scan/z_evolution_fine/    - per-case z-evolution CSVs (full res.)
    output_simulations/power_scan/all_lengths_scan_results.csv - multi-length sweep summary
